package ex2b.model.threads;

import ex2b.controller.Controller;
import ex2b.model.ThreadContext;

public class GUIThread extends Thread {
	private Controller controller = null;
	private ThreadContext[] producers, consumers;
	private int[] semaphores;
	
	public GUIThread() {
		int i = 0;
		controller = Controller.getInstance();
		producers = new ThreadContext[ controller.producers.length ];
		consumers = new ThreadContext[ controller.consumers.length ];
		semaphores = new int[ controller.semaphores.length ];
		
		for( i = 0; i < producers.length; ++i ) {
			producers[ i ] = new ThreadContext( controller.producers[ i ].getSemaphoreIndex(), controller.producers[ i ].getState() );
		}
		for( i = 0; i < consumers.length; ++i ) {
			consumers[ i ] = new ThreadContext( controller.consumers[ i ].getSemaphoreIndex(), controller.consumers[ i ].getState() );
		}
		for( i = 0; i < semaphores.length; ++i ) {
			semaphores[ i ] = controller.semaphores[ i ].availablePermits();
		}
		
	}
	
	public int[] getSemaphores() {
		return semaphores;
	}
	
	public ThreadContext[] getProducers() {
		return producers;
	}
	
	public ThreadContext[] getConsumers() {
		return consumers;
	}
	
	@Override
	public void run() {
		int i = 0;
		
		while( ! controller.finish ) {
			synchronized( controller ) {
				if( ! controller.isRunning() ) {
					try {
						controller.wait();
					} catch (InterruptedException e) {}
				}
			}
			
			for( i = 0; i < producers.length; ++i ) {
				producers[ i ].semaphoreIndex = controller.producers[ i ].getSemaphoreIndex();
				producers[ i ].state = controller.producers[ i ].getState();
			}
		
			for( i = 0; i < consumers.length; ++i ) {
				consumers[ i ].semaphoreIndex = controller.consumers [ i ].getSemaphoreIndex();
				consumers[ i ].state = controller.consumers[ i ].getState();
			}
			
			for( i = 0; i < semaphores.length; ++i ) {
				semaphores[ i ] = controller.semaphores[ i ].availablePermits();
			}
			
			controller.updateThreadsPanel();
			controller.updateProductsPanel();
			controller.updateSemaphoresPanel();
			
			try {
								
				sleep( controller.speed / 2 );
			
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	}
}
